export default class audioContext {
    constructor() {
        this.recorderManager = null;
        this.dataCallback = null;
        this.stopCallback = null;
        this.isRecording = false;
        this.platform = this.getPlatform();

        // H5平台相关属性
        this.mediaRecorder = null;
        this.audioChunks = [];
        this.stream = null;

        this.initRecorder();
    }

    // 获取当前平台
    getPlatform() {
        let platform = '';
        // #ifdef H5
        platform = 'h5';
        // #endif
        // #ifdef MP-WEIXIN
        platform = 'mp-weixin';
        // #endif

        // #ifdef APP-PLUS
        platform = 'app-plus';
        // #endif
        return platform;
    }

    initRecorder() {
        if (this.platform === 'h5') {
            this.initH5Recorder();
        } else if (this.platform === 'app-plus') {
            this.initAppRecorder();
        } else {
            this.initMiniProgramRecorder();
        }
    }

    // 初始化H5录音器
    initH5Recorder() {
        console.log('初始化H5录音器');
        // H5录音器的事件监听将在开始录音时设置
    }

    // 初始化APP录音器
    initAppRecorder() {
        console.log('初始化APP录音器');
        // 获取录音管理器
        this.recorderManager = uni.getRecorderManager();

        // 监听录音开始事件
        this.recorderManager.onStart(() => {
            console.log('APP录音开始');
            this.isRecording = true;
        });

        // 监听录音停止事件
        this.recorderManager.onStop(res => {
            this.isRecording = false;
            console.log('APP录音停止', res);

            if (this.stopCallback) {
                this.stopCallback(res);
            }
        });

        // 监听录音暂停事件
        this.recorderManager.onPause(() => {
            console.log('APP录音暂停');
        });

        // 监听录音恢复事件
        this.recorderManager.onResume(() => {
            console.log('APP录音恢复');
        });

        // 监听录音错误事件
        this.recorderManager.onError(err => {
            console.error('APP录音错误', err);
            this.isRecording = false;

            uni.showToast({
                title: '录音失败：' + err.errMsg,
                icon: 'none',
                duration: 3000,
            });
        });

        // 监听录音过程中的音频数据
        this.recorderManager.onFrameRecorded(res => {
            if (this.dataCallback) {
                this.dataCallback(res);
            }
        });
    }

    // 初始化小程序录音器
    initMiniProgramRecorder() {
        console.log('初始化小程序录音器');
        // 获取录音管理器
        this.recorderManager = uni.getRecorderManager();

        // 监听录音开始事件
        this.recorderManager.onStart(() => {
            console.log('录音开始');
            this.isRecording = true;
        });

        // 监听录音停止事件
        this.recorderManager.onStop(res => {
            this.isRecording = false;

            if (this.stopCallback) {
                this.stopCallback(res);
            }
        });

        // 监听录音暂停事件
        this.recorderManager.onPause(() => {
            console.log('录音暂停');
        });

        // 监听录音恢复事件
        this.recorderManager.onResume(() => {
            console.log('录音恢复');
        });

        // 监听录音错误事件
        this.recorderManager.onError(err => {
            console.error('录音错误', err);
            this.isRecording = false;

            uni.showToast({
                title: '录音失败：' + err.errMsg,
                icon: 'none',
                duration: 3000,
            });
        });

        // 监听录音过程中的音频数据
        this.recorderManager.onFrameRecorded(res => {
            if (this.dataCallback) {
                this.dataCallback(res);
            }
        });
    }

    // H5录音开始（重写，使用async/await和Permissions API，优先mp3格式）
    async startRecording() {
        if (this.platform === 'h5') {
            return this.startH5Recording();
        } else if (this.platform === 'app-plus') {
            return this.startAppRecording();
        } else {
            return this.startMiniProgramRecording();
        }
    }

    // H5录音开始
    async startH5Recording() {
        // 检查是否录音授权
        try {
            if (navigator.permissions) {
                const status = await navigator.permissions.query({ name: 'microphone' });
                if (status.state === 'denied') {
                    if (typeof Notify !== 'undefined') {
                        Notify.create({
                            message: '麦克风权限被拒绝，请在浏览器设置中开启麦克风权限',
                            type: 'error',
                        });
                    } else {
                        uni.showToast({
                            title: '麦克风权限被拒绝',
                            icon: 'none',
                        });
                    }
                    return;
                }
            }
            this.stream = await navigator.mediaDevices.getUserMedia({ audio: true });
        } catch (err) {
            if (typeof Notify !== 'undefined') {
                Notify.create({
                    message: '无法获取麦克风权限，请检查浏览器设置',
                    type: 'error',
                });
            } else {
                uni.showToast({
                    title: '无法获取麦克风权限',
                    icon: 'none',
                });
            }
            return;
        }

        // 优先mp3格式
        let mimeType = 'audio/mp3';
        if (!MediaRecorder.isTypeSupported(mimeType)) {
            if (MediaRecorder.isTypeSupported('audio/mpeg')) {
                mimeType = 'audio/mpeg';
            } else if (MediaRecorder.isTypeSupported('audio/webm;codecs=opus')) {
                mimeType = 'audio/webm;codecs=opus';
            } else if (MediaRecorder.isTypeSupported('audio/webm')) {
                mimeType = 'audio/webm';
            } else if (MediaRecorder.isTypeSupported('audio/mp4')) {
                mimeType = 'audio/mp4';
            } else {
                mimeType = 'audio/ogg';
            }
        }
        this.mediaRecorder = new window.MediaRecorder(this.stream, { mimeType });
        this.chunks = [];
        this._h5StartTime = Date.now();

        this.mediaRecorder.ondataavailable = e => {
            if (e.data && e.data.size > 0) {
                this.chunks.push(e.data);
                if (this.dataCallback) {
                    // 不在dataCallback返回blob，统一只在stop时返回
                }
            }
        };

        this.mediaRecorder.onstop = () => {
            const blob = new Blob(this.chunks, { type: mimeType });
            const tempFilePath = URL.createObjectURL(blob);
            const fileSize = blob.size;
            const duration = Date.now() - (this._h5StartTime || Date.now());
            const format = mimeType.split('/')[1].split(';')[0];
            if (this.stopCallback) {
                this.stopCallback({
                    tempFilePath,
                    duration,
                    fileSize,
                    format,
                    blob,
                });
            }
            // 释放麦克风
            if (this.stream) {
                this.stream.getTracks().forEach(track => track.stop());
                this.stream = null;
            }
        };

        this.mediaRecorder.start();
        this.isRecording = true;
    }

    // APP录音开始
    async startAppRecording() {
        // 检查录音权限
        const authResult = await this.checkRecordAuth();
        if (!authResult) {
            return;
        }

        // 开始录音
        this.recorderManager.start({
            duration: 600000, // 录音最长时间，单位 ms，默认 60s，最长 10分钟
            sampleRate: 24000, // 采样率
            numberOfChannels: 1, // 录音通道数
            format: 'mp3', // 音频格式，有效值 aac/mp3
            // APP特有配置
            // #ifdef APP-PLUS
            audioSource: 'auto', // 音频输入源，auto 自动选择，build_in_mic 内置麦克风
            // #endif
        });
    }

    // 小程序录音开始
    async startMiniProgramRecording() {
        // 检查录音权限

        // #ifdef MP-WEIXIN
        const authResult = await this.checkRecordAuth();
        if (!authResult) {
            return;
        }
        // #endif

        // 开始录音
        this.recorderManager.start({
            duration: 600000, // 录音最长时间，单位 ms，默认 60s，最长 10分钟
            sampleRate: 24000, // 采样率
            numberOfChannels: 1, // 录音通道数
            format: 'mp3', // 音频格式，有效值 aac/mp3
        });
    }

    // H5录音停止（重写，返回统一结构）
    stopRecording(callback) {
        if (this.platform === 'h5') {
            if (this.mediaRecorder && this.mediaRecorder.state !== 'inactive') {
                if (callback) {
                    // 临时回调，只执行一次
                    const once = res => {
                        callback(res);
                        this.onstop(null); // 清除临时回调
                    };
                    this.onstop(once);
                }
                this.mediaRecorder.stop();
                this.isRecording = false;
            }
        } else if (this.platform === 'app-plus') {
            // APP录音停止
            if (this.isRecording) {
                if (callback) {
                    const once = res => {
                        // APP返回结构，补充blob:null
                        callback({
                            tempFilePath: res.tempFilePath,
                            duration: res.duration,
                            fileSize: res.fileSize,
                            format: res.format || 'mp3',
                            blob: null,
                        });
                        this.onstop(null);
                    };
                    this.onstop(once);
                }
                this.recorderManager.stop();
                this.isRecording = false;
            }
        } else {
            // 小程序录音停止
            if (this.isRecording) {
                if (callback) {
                    const once = res => {
                        // 兼容小程序返回结构
                        callback({
                            tempFilePath: res.tempFilePath,
                            duration: res.duration,
                            fileSize: res.fileSize,
                            format: res.format || 'mp3',
                            blob: null,
                        });
                        this.onstop(null);
                    };
                    this.onstop(once);
                }
                this.recorderManager.stop();
            }
        }
    }

    pauseRecording() {
        if (this.isRecording) {
            if (this.platform === 'h5') {
                if (this.mediaRecorder && this.mediaRecorder.state === 'recording') {
                    this.mediaRecorder.pause();
                }
            } else if (this.platform === 'app-plus') {
                // APP录音暂停
                if (this.recorderManager) {
                    this.recorderManager.pause();
                }
            } else {
                // 小程序录音暂停
                this.recorderManager.pause();
            }
        }
    }

    resumeRecording() {
        if (this.platform === 'h5') {
            if (this.mediaRecorder && this.mediaRecorder.state === 'paused') {
                this.mediaRecorder.resume();
            }
        } else if (this.platform === 'app-plus') {
            // APP录音恢复
            if (this.recorderManager) {
                this.recorderManager.resume();
            }
        } else {
            // 小程序录音恢复
            if (this.recorderManager) {
                this.recorderManager.resume();
            }
        }
    }

    ondata(callback) {
        this.dataCallback = callback;
    }

    onstop(callback) {
        this.stopCallback = callback;
    }

    // 检查录音权限
    async checkRecordAuth() {
        if (this.platform === 'h5') {
            // H5平台权限检查在startH5Recording中处理
            return true;
        }

        // APP权限检查
        if (this.platform === 'app-plus') {
            return this.checkAppRecordAuth();
        }

        // 小程序权限检查
        return new Promise(resolve => {
            uni.authorize({
                scope: 'scope.record',
                success() {
                    resolve(true);
                },
                fail() {
                    uni.showModal({
                        title: '授权提示',
                        content: '需要录音权限才能使用语音功能',
                        showCancel: false,
                        confirmText: '去设置',
                        success: res => {
                            if (res.confirm) {
                                uni.openSetting({
                                    success: settingRes => {
                                        if (settingRes.authSetting['scope.record']) {
                                            resolve(true);
                                        } else {
                                            resolve(false);
                                        }
                                    },
                                    fail: () => {
                                        resolve(false);
                                    },
                                });
                            } else {
                                resolve(false);
                            }
                        },
                    });
                },
            });
        });
    }

    // APP录音权限检查
    async checkAppRecordAuth() {
        return new Promise(resolve => {
            // #ifdef APP-PLUS
            // Android平台
            // #ifdef APP-PLUS-ANDROID
            if (plus.os.name.toLowerCase() === 'android') {
                const main = plus.android.runtimeMainActivity();
                const Context = plus.android.importClass('android.content.Context');
                const PackageManager = plus.android.importClass(
                    'android.content.pm.PackageManager'
                );
                const Manifest = plus.android.importClass('android.Manifest');

                // 检查录音权限
                const hasPermission =
                    main.checkSelfPermission(Manifest.permission.RECORD_AUDIO) ===
                    PackageManager.PERMISSION_GRANTED;

                if (hasPermission) {
                    resolve(true);
                } else {
                    // 请求录音权限
                    uni.showModal({
                        title: '权限提示',
                        content: '需要录音权限才能使用语音功能，请在系统设置中开启麦克风权限',
                        showCancel: false,
                        confirmText: '去设置',
                        success: res => {
                            if (res.confirm) {
                                // 打开系统设置
                                plus.runtime.openURL('package:com.android.settings');
                                resolve(false);
                            } else {
                                resolve(false);
                            }
                        },
                    });
                }
            }
            // #endif

            // iOS平台
            // #ifdef APP-PLUS-IOS
            if (plus.os.name.toLowerCase() === 'ios') {
                // iOS权限检查
                const AVCaptureDevice = plus.ios.importClass('AVCaptureDevice');
                const status = AVCaptureDevice.authorizationStatusForMediaType('vide');

                if (status === 3) {
                    // AVAuthorizationStatusAuthorized
                    resolve(true);
                } else {
                    uni.showModal({
                        title: '权限提示',
                        content: '需要录音权限才能使用语音功能，请在系统设置中开启麦克风权限',
                        showCancel: false,
                        confirmText: '去设置',
                        success: res => {
                            if (res.confirm) {
                                // 打开系统设置
                                plus.runtime.openURL('App-Prefs:root=Privacy&path=MICROPHONE');
                                resolve(false);
                            } else {
                                resolve(false);
                            }
                        },
                    });
                }
                plus.ios.deleteObject(AVCaptureDevice);
            }
            // #endif
            // #endif

            // 其他平台默认返回true
            resolve(true);
        });
    }

    // 清理H5录音资源
    cleanup() {
        if (this.stream) {
            this.stream.getTracks().forEach(track => {
                track.stop();
            });
            this.stream = null;
        }

        this.audioChunks = [];
        this.mediaRecorder = null;
    }

    // 销毁录音管理器
    destroy() {
        if (this.platform === 'h5') {
            this.cleanup();
        } else {
            if (this.recorderManager) {
                this.recorderManager.stop();
                this.recorderManager = null;
            }
        }

        this.dataCallback = null;
        this.stopCallback = null;
        this.isRecording = false;
    }
}
